package middleware

import (
	"blog/core/request"
	"blog/utils"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type Auth struct {
}

func (receiver *Auth) IsLogin() gin.HandlerFunc {
	return func(context *gin.Context) {
		req := request.Request(context)
		auth := context.GetHeader("Authorization")
		if !strings.Contains(auth, "Bearer ") {
			req.Response().Message("token不存在").Error()
			context.Abort()
			return
		}

		token := strings.TrimSpace(strings.TrimLeft(auth, "Bearer"))
		unToken, ok := utils.DeToken(token)
		if !ok {
			req.Response().Message("token不正确").Error()
			context.Abort()
		}

		expTime := int64(unToken["exp"].(float64))
		if expTime < time.Now().Unix() {
			req.Response().Message("token已过期").Error()
			context.Abort()
		}

		context.Next()
	}
}
